package com.heima.admin.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.heima.admin.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
@Order(-1)
public class AuthorizeFilter implements GlobalFilter {
    //白名单集合
    private final static List<String> urlList = new ArrayList<>();

    //添加白名单路径
    //初始化白名单 url路径
    static {
        urlList.add("/login/in");
        urlList.add("/v2/api-docs");
    }

    //过滤
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //判断请求路径是否在白名单
        //得到请求路径  /login/in
        String path = request.getURI().getPath();
        //在白名单直接放行
        for (String urlPath : urlList) {
            if (path.contains(urlPath)) {
                return chain.filter(exchange);
            }
        }
        //获取请求头中的token
        String token = request.getHeaders().getFirst("token");
        //不存在token返回401
        if (StringUtils.isBlank(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return writeMessage(exchange, "需要登录!");
        }
        try {
            //使用jwt工具类解析token
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //拿到状态码
            int status = AppJwtUtil.verifyToken(claimsBody);
            //判断状态是否大于1
            if (status > 1) {
                return writeMessage(exchange, "用户认证失败!");
            }
            //获取userId
            if (claimsBody != null) {
                Object id = claimsBody.get("id");
                //将userId设置到请求头中
                request.mutate().header("userId", String.valueOf(id)).build();
                exchange.mutate().request(request).build();

            }
            //放行
            return chain.filter(exchange);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("token校验失败 : {}", e.getMessage());
            //解析失败  返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return writeMessage(exchange, "认证失败请重新登录");
        }
    }

    /**
     * 返回错误提示信息
     *
     * @return
     */
    private Mono<Void> writeMessage(ServerWebExchange exchange, String message) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("errorMessage", message);
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //response.setStatusCode(HttpStatus.OK);
        //设置返回类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //设置返回数据
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONBytes(map));
        //响应数据回浏览器
        return response.writeWith(Flux.just(buffer));
    }
}
